extends Control
class_name VirtualJoysticks02

signal sOnInput
var startPos:Vector2
var movePos:Vector2
var lastPos:Vector2
var started:bool = false
var ipt:Vector2 = Vector2.ZERO

var pressCount = 0
var releaseCount = 0
var moveCount = 0

@export var touchRadius = 10
@export var moveScale = 1.0
@export var friction = 50

@onready var touchPos = $Control/TouchPos
@onready var uiParent = $Control


func _ready():
	uiParent.modulate.a = 0.0


func _unhandled_input(event):
	if event is InputEventMouseButton:
		if event.pressed:
			onPress(event.position)
		else:
			onRelease(event.position)
	elif event is InputEventMouseMotion:
		onMove(event.position)
		

func handlePress(pos):
	started = true
	startPos = pos
	movePos = startPos
	lastPos = movePos
	ipt = Vector2.ZERO
	uiParent.modulate.a = 1.0
	
	pressCount += 1
			

func handleRelease():
	started = false
	startPos = Vector2.ZERO
	movePos = Vector2.ZERO
	lastPos = Vector2.ZERO
	ipt = Vector2.ZERO
	uiParent.modulate.a = 0.0
	
	releaseCount += 1


func handleMove(pos):
	if not started: 
		return
		
	lastPos =  movePos
	movePos = pos
	
	moveScale = 1.0
	
	moveCount += 1


func onPress(pos):
	handlePress(pos)
	

func onRelease(pos):
	handleRelease()
	
	
func onMove(pos):
	handleMove(pos)
	

func _physics_process(delta):
	if started:
		calcVelocity(delta)
	sOnInput.emit(ipt)
	
	updateUI()
	
	#var msg = "startPos: " + str(startPos) + "\nmovePos: " + str(movePos) + "\nlastPos: " + str(lastPos)+"\nipt: " + str(ipt) + "\npressCount: " + str(pressCount) + "\nreleaseCount: " + str(releaseCount) + "\nmoveCount: " + str(moveCount)
	#Global.signalDebugMessage.emit(msg)


func calcVelocity(delta):
	ipt = (movePos - lastPos) * moveScale
	moveScale = lerp(moveScale, 0.0, friction * delta)

	
func updateUI():
	touchPos.setPos(movePos)
	touchPos.setRadius(touchRadius)
	
